﻿using System;
using System.Data;
using System.Web.UI.WebControls;


public partial class TestGrafic : System.Web.UI.Page
{
    private readonly string mCurrentModule = Credits.Module.ID;
    private readonly string mPageName = "Vizualizarea test a unui grafic de achitari";
    private string appPath = string.Empty;

    bool allowLoanView = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        appPath = Utils.GetApplicationPath(Request);
        Utils.GetMaster(this).PerformPreloadActions(mCurrentModule, mPageName);

        try
        {
            allowLoanView = Utils.PermissionAllowed(mCurrentModule, Credits.Domains.ManageLoans.Name, Constants.Constants.Classifiers.Permissions_View);
         
            if (allowLoanView)
            {
                loanStartDateCalendarExtender.Format = Constants.Constants.ISODateBackwardDotsFormat;
                //printLoanButton.OnClientClick = "javascript:CallPrint('" + PreviewCreditForm.ClientID + "');";

                if (!IsPostBack)
                {
                    SetInitialRowForNewClientsTable();
                    contractPercentTextBox.Attributes.Add("onKeyUp", "CalculateAlernativePercent(this.value, '" + alternativePercentTextBox.ClientID + "');");
                    alternativePercentTextBox.Attributes.Add("onKeyUp", "CalculateAlernativePercent2(this.value, '" + contractPercentTextBox.ClientID + "');");  
                    
                    DataTable payperiodList = Utils.ModuleMain().GetClassifierByTypeID((int)Constants.Constants.ClassifierTypes.PayPeriod);
                    Utils.FillSelector(payPeriodDDL, payperiodList, "Name", "Code");

                    DataTable currencyDT = new DataTable();
                    currencyDT.Columns.Add("code", typeof(int));
                    currencyDT.Columns.Add("name", typeof(string));
                    currencyDT.Rows.Add((int)Constants.Constants.CurrencyList.USD, "USD");
                    currencyDT.Rows.Add((int)Constants.Constants.CurrencyList.EURO, "EURO");
                    Utils.FillSelector(currencyDDL, currencyDT, "Name", "Code");   

                    try
                    { currencyDDL.SelectedValue = ((int)Constants.Constants.CurrencyList.USD).ToString(); }
                    catch { }

                    try
                    { payPeriodDDL.SelectedValue = ((int)Constants.Constants.Classifiers.MonthlyPayment).ToString(); }
                    catch { }

                    //SetChangeRate();
                    PreviewCreditForm.Visible = false;
                    loandDataEliberariiTextBox.Text = DateTime.Now.Date.ToString(Constants.Constants.ISODateBackwardDotsFormat);
                }

                if (Request.Params.Get("__EVENTTARGET") == "UpdateBeforPrint")
                {
                    SaveLastChangesInManualEditCreditGridView();
                    UpdateManualEditCreditGridView();
                    CalculateTotalsLabelOnManualEditGridView();
                    System.Web.UI.ScriptManager.RegisterStartupScript(previewUpdatePanel, typeof(string), "PrintPreview", "graficPrintPreview('" + PreviewCreditForm.ClientID + "', '3', '" + manualEditCreditGridView.ClientID + "')", true);
                }                    
            }                
            else
            {
                Response.Redirect(Utils.GetApplicationPath(Request) + "/AccessDenied.aspx");
            }
        }
        catch (Exception ex)
        { Utils.InfoText(this, "Eroare in System!", ex.Message.ToString()); }     
    }
    
    protected void previewLoanButton_Click(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected void PreviewOrderTabel()
    {
        decimal currencyChangeRate = Crypt.Utils.MyDecimalParce(currencyChangeRateTextBox.Text);

        if (currencyDDL.SelectedValue.Equals(((int)Constants.Constants.CurrencyList.USD).ToString()))
        { currencyLabel.Text = "Cursul Dolarului:"; }
        else
        { currencyLabel.Text = "Cursul Euro:"; }

        ViewState[manualEditCreditCurrentTable] = PrepareLoanOrders(currencyChangeRate);
        UpdateManualEditCreditGridView();
        CalculateTotalsLabelOnManualEditGridView();

        #region General Labels
        
        loanAmountLabel.Text = contractAmountTextBox.Text;
        loanNrOfPaymnetsLabel.Text = loanNrOfMonthsTextBox.Text;
        loanStartDateLabel.Text = loandDataEliberariiTextBox.Text;
        loanPercetLabel.Text = contractPercentTextBox.Text;

        if (calculateDinSoldInitialRadioButton.Checked)
            loanCalculationMetodLabel.Text = calculateDinSoldInitialRadioButton.Text;
        if (calculateDinSoldRamasRadioButton.Checked)
            loanCalculationMetodLabel.Text = calculateDinSoldRamasRadioButton.Text;

        currencyChangeRatelabel.Text = currencyChangeRate.ToString();

        decimal contractAmount = Crypt.Utils.MyDecimalParce(contractAmountTextBox.Text);
        if (currencyChangeRate > 0)
            loanAmountInUSDLabel.Text = Math.Round(contractAmount / currencyChangeRate, 2).ToString();    
          
        #endregion General Labels
    }

    protected void contractAmountTextBox_TextChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }
    
    protected void loanNrOfMonthsTextBox_TextChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected void gracePeriodTextBox_TextChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected void contractPercentTextBox_TextChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected void payPeriodDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected void calculateDinSoldInitialRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected void loanChangeRateTextBox_TextChanged(object sender, EventArgs e)
    {
        PreviewOrderTabel();
    }

    protected DataTable PrepareLoanOrders(decimal currencyChangeRate)
    {
        DateTime loanStartDate = Crypt.Utils.ToDateTime(loandDataEliberariiTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);

        decimal creditAmount = Crypt.Utils.MyDecimalParce(contractAmountTextBox.Text);
        decimal creditPercent = Crypt.Utils.MyDecimalParce(contractPercentTextBox.Text);

        int nrTotalLuniACreditului = 0;
        int.TryParse(loanNrOfMonthsTextBox.Text, out nrTotalLuniACreditului);
        
        int payPeriodCode = 0;
        int.TryParse(payPeriodDDL.SelectedValue, out payPeriodCode);

        int calculatePernectFromCode = 0;
        if (calculateDinSoldInitialRadioButton.Checked) calculatePernectFromCode = (int)Constants.Constants.Classifiers.Percent_DinSumaInitiala;
        if (calculateDinSoldRamasRadioButton.Checked) calculatePernectFromCode = (int)Constants.Constants.Classifiers.Percent_DinSumaRamasa;

        DateTime loanEdnDate = DateTime.MinValue;
        DataTable grafic = Credits.Module.PrepareOrdersTable(loanStartDate, creditAmount, creditPercent, nrTotalLuniACreditului, payPeriodCode, calculatePernectFromCode, currencyChangeRate, out loanEdnDate);
        grafic.Columns.Add("modifiedMainRate", typeof(bool));

        loanDataScadenteiTextBox.Text = loanEdnDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);

        return grafic;
    }
     
    #region Manual Edit Credit

    private void SetInitialRowForNewClientsTable()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("iterationID", typeof(string)));
        dt.Columns.Add(new DataColumn("calculatedData", typeof(DateTime)));
        dt.Columns.Add(new DataColumn("days", typeof(int)));
        dt.Columns.Add(new DataColumn("percentValue", typeof(decimal)));
        dt.Columns.Add(new DataColumn("mainRate", typeof(decimal)));
        dt.Columns.Add(new DataColumn("modifiedMainRate", typeof(bool)));
        dt.Columns.Add(new DataColumn("TotalAmount", typeof(decimal)));
        dt.Columns.Add(new DataColumn("remainingAmount", typeof(decimal)));
        dt.Columns.Add(new DataColumn("currencyChangeRate", typeof(decimal)));
        dt.Columns.Add(new DataColumn("totalAmount_Rated", typeof(decimal)));

        dr = dt.NewRow();
        dr["iterationID"] = 1;

        dt.Rows.Add(dr);

        //Store the DataTable in ViewState
        ViewState[manualEditCreditCurrentTable] = dt;
        manualEditCreditGridView.DataSource = dt;
        manualEditCreditGridView.DataBind();
    }

    private void UpdateManualEditCreditGridView()
    {
        if (ViewState[manualEditCreditCurrentTable] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState[manualEditCreditCurrentTable];

            if (dtCurrentTable != null)
            {
                manualEditCreditGridView.DataSource = dtCurrentTable;
                manualEditCreditGridView.DataBind();
                PreviewCreditForm.Visible = true;

                DateTime maxModifiedDate = DateTime.MinValue;

                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    Label nrLabel = (Label)manualEditCreditGridView.Rows[i].Cells[0].FindControl("nrLabel");
                    TextBox manualEditCreditDataTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[1].FindControl("manualEditCreditDataTextBox");
                    TextBox daysLabel = (TextBox)manualEditCreditGridView.Rows[i].Cells[2].FindControl("daysLabel");
                    TextBox manualEditCreditRemainingAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[3].FindControl("manualEditCreditRemainingAmountTextBox");
                    TextBox manualEditMainRateTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateTextBox");
                    HiddenField manualEditMainRateModifiedHiddenField = (HiddenField)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateModifiedHiddenField");
                    TextBox percentTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[5].FindControl("percentTextBox");
                    TextBox manualEditCreditTotalAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[6].FindControl("manualEditCreditTotalAmountTextBox");
                    TextBox manualEditCreditTotalAmount_RatedTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[7].FindControl("manualEditCreditTotalAmount_RatedTextBox");
                   

                    nrLabel.Text = (i + 1).ToString();

                    DateTime calculatedDate = dtCurrentTable.Rows[i]["calculatedData"] != System.DBNull.Value ? ((DateTime)dtCurrentTable.Rows[i]["calculatedData"]) : DateTime.MinValue;
                    manualEditCreditDataTextBox.Text = calculatedDate != DateTime.MinValue ? calculatedDate.ToString(Constants.Constants.ISODateBackwardDotsFormat) : string.Empty;
                    if (calculatedDate > maxModifiedDate)
                    {
                        maxModifiedDate = calculatedDate;
                    }

                    daysLabel.Text = dtCurrentTable.Rows[i]["days"] != System.DBNull.Value ? (dtCurrentTable.Rows[i]["days"]).ToString() : string.Empty;
                    manualEditCreditRemainingAmountTextBox.Text = dtCurrentTable.Rows[i]["remainingAmount"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["remainingAmount"].ToString() : string.Empty;
                    manualEditMainRateTextBox.Text = dtCurrentTable.Rows[i]["mainRate"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["mainRate"].ToString() : string.Empty;
                    percentTextBox.Text = dtCurrentTable.Rows[i]["percentValue"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["percentValue"].ToString() : string.Empty;                   
                    manualEditCreditTotalAmountTextBox.Text = dtCurrentTable.Rows[i]["TotalAmount"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["TotalAmount"].ToString() : string.Empty;                    
                    manualEditCreditTotalAmount_RatedTextBox.Text = dtCurrentTable.Rows[i]["TotalAmount_Rated"] != System.DBNull.Value ? dtCurrentTable.Rows[i]["TotalAmount_Rated"].ToString() : string.Empty;

                    manualEditMainRateModifiedHiddenField.Value = dtCurrentTable.Rows[i]["modifiedMainRate"] != System.DBNull.Value && (bool)dtCurrentTable.Rows[i]["modifiedMainRate"] == true ? "true" : "false";
                  
                    /// manual  add  events

                    //manualEditCreditDataTextBox.Attributes.Add("onchange", "CalculateData(this, " + (i + 1).ToString() + ");");
                    //manualEditCreditDataTextBox.Attributes.Add("onKeyUp", "CalculateData(this, " + (i + 1).ToString() + ");");

                    manualEditMainRateTextBox.Attributes.Add("onKeyUp", "ModifiedRate(" + (i + 1).ToString() + ", '" + manualEditCreditGridView.ClientID + "', '" + contractAmountTextBox.ClientID + "', '" + loandDataEliberariiTextBox.ClientID + "', '" + loanDataScadenteiTextBox.ClientID + "', '" + contractPercentTextBox.ClientID + "', '" + calculateDinSoldInitialRadioButton.ClientID + "', '" + currencyChangeRateTextBox.ClientID + "','" + loanNrOfMonthsTextBox.ClientID + "', '" + payPeriodDDL.ClientID + "');");
                    manualEditCreditTotalAmountTextBox.Attributes.Add("onKeyUp", "ModifiedTotalAmount(" + (i + 1).ToString() + ", '" + manualEditCreditGridView.ClientID + "', '" + contractAmountTextBox.ClientID + "', '" + loandDataEliberariiTextBox.ClientID + "', '" + loanDataScadenteiTextBox.ClientID + "', '" + contractPercentTextBox.ClientID + "', '" + calculateDinSoldInitialRadioButton.ClientID + "', '" + currencyChangeRateTextBox.ClientID + "','" + loanNrOfMonthsTextBox.ClientID + "', '" + payPeriodDDL.ClientID + "');");

                    percentTextBox.Attributes.Add("readonly", "readonly");
                    daysLabel.Attributes.Add("readonly", "readonly");
                    manualEditCreditRemainingAmountTextBox.Attributes.Add("readonly", "readonly");
                }

                if (maxModifiedDate != DateTime.MinValue)
                    loanDataScadenteiTextBox.Text = maxModifiedDate.ToString(Constants.Constants.ISODateBackwardDotsFormat);
            }
        }
    }
    
    private DataTable SaveLastChangesInManualEditCreditGridView()
    {
        DataTable dtCurrentTable = null;

        if (ViewState[manualEditCreditCurrentTable] != null)
        {
            dtCurrentTable = (DataTable)ViewState[manualEditCreditCurrentTable];

            if (dtCurrentTable != null)
            {
                for (int i = 0; i < dtCurrentTable.Rows.Count; i++)
                {
                    Label nrLabel = (Label)manualEditCreditGridView.Rows[i].Cells[0].FindControl("nrLabel");
                    TextBox manualEditCreditDataTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[1].FindControl("manualEditCreditDataTextBox");
                    TextBox daysLabel = (TextBox)manualEditCreditGridView.Rows[i].Cells[2].FindControl("daysLabel");
                    TextBox manualEditCreditRemainingAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[3].FindControl("manualEditCreditRemainingAmountTextBox");
                    TextBox manualEditMainRateTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateTextBox");
                    TextBox percentTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[5].FindControl("percentTextBox");
                    TextBox manualEditCreditTotalAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[6].FindControl("manualEditCreditTotalAmountTextBox");
                    TextBox manualEditCreditTotalAmount_RatedTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[7].FindControl("manualEditCreditTotalAmount_RatedTextBox");
                    
                    HiddenField manualEditMainRateModifiedHiddenField = (HiddenField)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateModifiedHiddenField");                    
                    
                    dtCurrentTable.Rows[i]["iterationID"] = (i + 1).ToString();

                    if (!manualEditCreditDataTextBox.Text.Equals(string.Empty))
                    {
                        DateTime tempDate = Crypt.Utils.ToDateTime(manualEditCreditDataTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
                        if (!tempDate.Equals(DateTime.MinValue)) dtCurrentTable.Rows[i]["calculatedData"] = tempDate;
                    }
                    
                    if (!percentTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(percentTextBox.Text);
                        dtCurrentTable.Rows[i]["percentValue"] = tempVal;
                    }

                    if (!daysLabel.Text.Equals(string.Empty))
                    {
                        int tempVal = 0;
                        int.TryParse(daysLabel.Text, out tempVal);
                        dtCurrentTable.Rows[i]["days"] = tempVal;
                    }

                    if (!manualEditMainRateTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditMainRateTextBox.Text);
                        dtCurrentTable.Rows[i]["mainRate"] = tempVal;
                    }

                    if (!manualEditCreditTotalAmountTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmountTextBox.Text);
                        dtCurrentTable.Rows[i]["TotalAmount"] = tempVal;
                    }

                    if (!manualEditCreditRemainingAmountTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditCreditRemainingAmountTextBox.Text);
                        dtCurrentTable.Rows[i]["remainingAmount"] = tempVal;
                    }

                    if (!manualEditCreditTotalAmount_RatedTextBox.Text.Equals(string.Empty))
                    {
                        decimal tempVal = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmount_RatedTextBox.Text);
                        dtCurrentTable.Rows[i]["TotalAmount_Rated"] = tempVal;
                    }
                   
                    dtCurrentTable.Rows[i]["modifiedMainRate"] = manualEditMainRateModifiedHiddenField.Value.Equals("true");
                }
            }
        }
        else
        {
            Utils.InfoText(this, "Error on page!", "ViewState is null");
        }

        ViewState[manualEditCreditCurrentTable] = dtCurrentTable;
        return dtCurrentTable;
    }

    private void AddNewRowToGrid()
    {
        DataTable dtCurrentTable = SaveLastChangesInManualEditCreditGridView();
        UpdateManualEditCreditGridView();

        if (dtCurrentTable != null && dtCurrentTable.Columns.Count > 0)
        {
            dtCurrentTable.Rows.Add();
            dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["iterationID"] = dtCurrentTable.Rows.Count;

            if(dtCurrentTable.Rows.Count > 2 && dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["calculatedData"] != System.DBNull.Value)
            {
                DateTime previousDate = (DateTime)dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["calculatedData"];
                DateTime newEnteredDate = previousDate.AddMonths(1);
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["calculatedData"] = newEnteredDate;
                int days = (newEnteredDate - previousDate).Days;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["days"] = days;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["percentValue"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["mainRate"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["TotalAmount"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["remainingAmount"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["currencyChangeRate"] = 0;
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["totalAmount_Rated"] = 0;
            }

            loanNrOfMonthsTextBox.Text = dtCurrentTable.Rows.Count.ToString();

            ViewState[manualEditCreditCurrentTable] = dtCurrentTable;
        }

        UpdateManualEditCreditGridView();
        System.Web.UI.ScriptManager.RegisterStartupScript(previewUpdatePanel, typeof(string), "CalculateNewLoanOrders", "CalculateNewLoanOrders( '" + manualEditCreditGridView.ClientID + "', '" + contractAmountTextBox.ClientID + "', '" + loandDataEliberariiTextBox.ClientID + "', '" + loanDataScadenteiTextBox.ClientID + "', '" + contractPercentTextBox.ClientID + "', '" + calculateDinSoldInitialRadioButton.ClientID + "', '" + currencyChangeRateTextBox.ClientID + "')", true);                                                                                                                       
    }

    protected void manualEditCreditButtonAdd_Click(object sender, EventArgs e)
    {
        AddNewRowToGrid();
        CalculateTotalsLabelOnManualEditGridView();
    }

    protected void manualEditCreditGridView_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
    {
        int index = e.RowIndex;

        DataTable dtCurrentTable = SaveLastChangesInManualEditCreditGridView();
        UpdateManualEditCreditGridView();

        if (dtCurrentTable != null && dtCurrentTable.Columns.Count > 0)
        {
            dtCurrentTable.Rows[index].Delete();
            dtCurrentTable.AcceptChanges();

            loanNrOfMonthsTextBox.Text = dtCurrentTable.Rows.Count.ToString();
            ViewState[manualEditCreditCurrentTable] = dtCurrentTable;
        }

        SaveLastChangesInManualEditCreditGridView();
        UpdateManualEditCreditGridView();
        System.Web.UI.ScriptManager.RegisterStartupScript(previewUpdatePanel, typeof(string), "CalculateNewLoanOrders", "CalculateNewLoanOrders( '" + manualEditCreditGridView.ClientID + "', '" + contractAmountTextBox.ClientID + "', '" + loandDataEliberariiTextBox.ClientID + "', '" + loanDataScadenteiTextBox.ClientID + "', '" + contractPercentTextBox.ClientID + "', '" + calculateDinSoldInitialRadioButton.ClientID + "', '" + currencyChangeRateTextBox.ClientID + "')", true);                                                                                                                       
    }

    private const string manualEditCreditCurrentTable = "manualEditCreditCurrentTable";

    private void CalculateTotalsLabelOnManualEditGridView()
    {
        decimal totalPercent = 0;
        decimal totalMainRate = 0;
        decimal totalAmount = 0;
        decimal totalDays = 0;
        decimal totalAmountRated = 0;
        decimal initialAmount = Crypt.Utils.MyDecimalParce(contractAmountTextBox.Text);

        if (manualEditCreditGridView != null && manualEditCreditGridView.Rows != null)
        {
            for (int i = 0; i < manualEditCreditGridView.Rows.Count; i++)
            {
                TextBox daysLabel = (TextBox)manualEditCreditGridView.Rows[i].Cells[2].FindControl("daysLabel");
                TextBox manualEditMainRateTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[4].FindControl("manualEditMainRateTextBox");
                TextBox percentTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[5].FindControl("percentTextBox");
                TextBox manualEditCreditTotalAmountTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[6].FindControl("manualEditCreditTotalAmountTextBox");
                TextBox manualEditCreditTotalAmount_RatedTextBox = (TextBox)manualEditCreditGridView.Rows[i].Cells[7].FindControl("manualEditCreditTotalAmount_RatedTextBox");

                decimal tempTotalDays = Crypt.Utils.MyDecimalParce(daysLabel.Text);
                totalDays += tempTotalDays;

                decimal tempPercent = Crypt.Utils.MyDecimalParce(percentTextBox.Text);
                totalPercent += tempPercent;

                decimal tempMainrate = Crypt.Utils.MyDecimalParce(manualEditMainRateTextBox.Text);
                totalMainRate += tempMainrate;

                decimal temptotalAmount = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmountTextBox.Text);
                totalAmount += temptotalAmount;

                decimal temptotalAmountRated = Crypt.Utils.MyDecimalParce(manualEditCreditTotalAmount_RatedTextBox.Text);
                totalAmountRated += temptotalAmountRated;
            }

            Label totalDaysLabel = manualEditCreditGridView.FooterRow.FindControl("totalDaysLabel") as Label;
            if (totalDaysLabel != null)
            {
                totalDaysLabel.Text = totalDays.ToString();
            }

            Label manualEditCreditTotalProcetLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalProcetLabel") as Label;
            if (manualEditCreditTotalProcetLabel != null)
            {
                manualEditCreditTotalProcetLabel.Text = totalPercent.ToString();
            }

            Label manualEditCreditTotalmainRateLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalmainRateLabel") as Label;
            if (manualEditCreditTotalmainRateLabel != null)
            {
                manualEditCreditTotalmainRateLabel.Text = totalMainRate.ToString();
            }

            Label manualEditCreditTotalAmountLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalAmountLabel") as Label;
            if (manualEditCreditTotalAmountLabel != null)
            {
                manualEditCreditTotalAmountLabel.Text = totalAmount.ToString();
            }

            Label manualEditCreditTotalTotalAmount_RatedLabel = manualEditCreditGridView.FooterRow.FindControl("manualEditCreditTotalTotalAmount_RatedLabel") as Label;
            if (manualEditCreditTotalTotalAmount_RatedLabel != null)
            {
                manualEditCreditTotalTotalAmount_RatedLabel.Text = totalAmountRated.ToString();
            }
        }
    }

    #endregion Manual Edit Credit

    protected void CheckRate()
    {
        DateTime checkedDate = Crypt.Utils.ToDateTime(loandDataEliberariiTextBox.Text, Constants.Constants.ISODateBackwardDotsFormat);
        int currencyID = 0;
        int.TryParse(currencyDDL.SelectedValue, out  currencyID);

        decimal currencyChangeRate = Utils.ModuleCredits().GetCurrencyRateByDate(checkedDate, currencyID);
        currencyChangeRateTextBox.Text = currencyChangeRate.ToString();
    }

    protected void currencyDDL_SelectedIndexChanged(object sender, EventArgs e)
    {
        CheckRate();
        PreviewOrderTabel();
    }

    protected void checkRateButton_Click(object sender, EventArgs e)
    {
        CheckRate();
    }
}